﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utility1;
using System.Net.Mail;
using System.Net;

namespace Thv.trangchu.page
{
    public partial class Site1 : System.Web.UI.MasterPage
    {
        Page_tb page = new Page_tb();
        protected string templatePath = string.Empty;
        IList<Page_tb> list1 = new List<Page_tb>();
        IList<Page_tb> list2 = new List<Page_tb>();
        IList<Page_tb> list3 = new List<Page_tb>();

        DataClasses1DataContext dx = new DataClasses1DataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            templatePath = WebUtils.GetBaseUrl();

            string thoat = "";
            try
            {
                thoat = Request.QueryString["thoat"].ToString() + "";
            }
            catch (Exception) { }
            if (thoat == "true")
                Session.RemoveAll();
            UserDB user_obj = (UserDB)Session[Global.SESS_SECURITY_CODE];

            if (user_obj == null)
            {
                hdfTrangthai.Value = "<a href=" + '"' + "#login-box" + '"' + "style=" + '"' + "color:White" + ";text-decoration:None" + '"' + " class=" + '"' + "login-window" + '"' + ">Đăng nhập </a>";
                //hdfCanhan.Value = "<dx:ASPxHyperLink ID=" + '"' + "dangky" + '"' + " runat=" + '"' + "server" + '"' + " ClientSideEvents-Click=" + '"' + "function(s, e) { ShowCreateAccountWindow(); }" + '"' + " Text=" + '"' + "Đăng ký" + '"' + "></dx:ASPxHyperLink>";
                hdfCanhan.Value = "";
                link1.Visible = true;
            }
            else
            {
                hdfTrangthai.Value = "<a href=" + '"' + templatePath + "/Ca-nhan/Hom-nay/Bang-tin.html" + '"' + "style=" + '"' + "color:White" + ";text-decoration:None" + '"' + " class=" + '"' + "login-window1" + '"' + ">" + user_obj.UserName + " </a>";
                hdfCanhan.Value = "<a href=" + '"' + templatePath + "/trangchu/page/thoat.html" + '"' + "style=" + '"' + "color:White" + ";text-decoration:None" + '"' + " class=" + '"' + "login1-window1" + '"' + ">Thoát </a>";
                link1.Visible = false;
            }
            if (!IsPostBack)
            {
                LoadDB();
                LoadQuangCaoSP();
                binngaysinh();
            }
        }


        #region Load data

        void LoadDB()
        {
            //*********************************************************
            var menu = from k in dx.GetTable<Menu_tb>()
                       where k.Loai == 1 && k.flag == true
                       orderby k.vitri ascending
                       select k;
            rptMenu1.DataSource = menu;
            rptMenu1.DataBind();

           

            var menubar = from mb in dx.GetTable<MenusBar>()
                          where mb.flag == true
                          select mb;
            rptMenubar.DataSource = menubar;
            rptMenubar.DataBind();
        }

        #endregion

        #region Event

        protected void rptMenu1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //load menu con theo menu category 

            Menu_tb cat = (Menu_tb)e.Item.DataItem;
            Repeater rptProduct = (Repeater)e.Item.FindControl("rptProduct1");//tim rptProduct con trong rptCategory 

            if (rptProduct != null)
            {
                IList<Menu_tb> list = getByMenuID(cat.ID, 2);
                if (list != null && list.Count != 0)
                {
                    rptProduct.DataSource = list;
                    rptProduct.DataBind();
                }
            }
        }

        protected void rptMenu2_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //load menu con theo menu category 

            Menu_tb cat = (Menu_tb)e.Item.DataItem;
            Repeater rptProduct = (Repeater)e.Item.FindControl("rptProduct2");//tim rptProduct con trong rptCategory 

            if (rptProduct != null)
            {
                IList<Page_tb> list = getByMenuID2(cat.ID, 2);
                if (list != null && list.Count != 0)
                {
                    rptProduct.DataSource = list;
                    rptProduct.DataBind();
                }
            }
        }
       

        protected void rptQC_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            ListItemQC cat = (ListItemQC)e.Item.DataItem;
            Repeater rptProduct = (Repeater)e.Item.FindControl("rptQuangCao");

            if (rptProduct != null)
            {
                IList<QuangCao> list = getByQC(cat.ID, 3);
                if (list != null && list.Count != 0)
                {
                    rptProduct.DataSource = list;
                    rptProduct.DataBind();
                }
            }
        }

        protected void rptMenubar_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            MenusBar cat = (MenusBar)e.Item.DataItem;
            Repeater rptProduct = (Repeater)e.Item.FindControl("rptMenubar1");

            if (rptProduct != null)
            {
                IList<MenuBarSub> list = getByMenuBar(cat.ID);
                if (list != null && list.Count != 0)
                {
                    rptProduct.DataSource = list;
                    rptProduct.DataBind();
                }
            }
        }

        #endregion

        #region Bindata by category

        public IList<Menu_tb> getByMenuID(int catid, int loai)
        {
            try
            {

                var menulst = from k in dx.GetTable<Menu_tb>()
                              where k.parenID == catid && k.Loai == loai && k.flag == true
                              select k;
               
                IList<Menu_tb> list = new List<Menu_tb>();
                foreach (Menu_tb pp in menulst)
                {
                    list.Add(pp);

                }
                return list;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        public IList<Page_tb> getByMenuID2(int catid, int loai)
        {
            try
            {
        
                var menulst = from k in dx.GetTable<Page_tb>()
                              where k.menuID == catid && k.Loai == loai && k.flag == true
                              select k;
                IList<Page_tb> list = new List<Page_tb>();
                foreach (Page_tb pp in menulst)
                {
                    list.Add(pp);
                    if (loai == 1)
                        list1.Add(pp);
                    else if (loai == 2)
                        list2.Add(pp);
                    else
                        list3.Add(pp);
                }
                return list;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public IList<QuangCao> getByQC(int catid, int loai)
        {
            try
            {

                var menulst = from k in dx.GetTable<QuangCao>()
                              where k.ListItemID == catid && k.DanhMucID == loai && k.flag == true
                              select k;
                IList<QuangCao> list = new List<QuangCao>();
                foreach (QuangCao pp in menulst)
                {
                    list.Add(pp);

                }
                return list;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public IList<MenuBarSub> getByMenuBar(int catid)
        {
            try
            {

                var menulst = from k in dx.GetTable<MenuBarSub>()
                              where k.BarID == catid && k.flag == true
                              select k;
                IList<MenuBarSub> list = new List<MenuBarSub>();
                foreach (MenuBarSub pp in menulst)
                {
                    list.Add(pp);

                }
                return list;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

        #region Bin data QuangCao
        void LoadQuangCaoSP()
        {

            //var show = from k in dx.GetTable<QuangCao>()
            //          where k.DanhMucID==3 && k.flag==true && k.ListItemID==1
            //          select k;
            //rptQuangCao.DataSource = show;
            //rptQuangCao.DataBind();

            //var show2 = from k in dx.GetTable<QuangCao>()
            //           where k.DanhMucID == 3 && k.flag == true && k.ListItemID == 2
            //           select k;
            //Repeater1.DataSource = show;
            //Repeater1.DataBind();

        }
        #endregion
        protected void LoginWebsite(object sender, EventArgs e)
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            var login = from k in dx.UserDBs
                        where k.flag == 1 && k.UserName == txtName.Text && k.Password == Global.ToEncoding(txtPass.Text)
                        select k;
            //IList<UserDB> list = new List<UserDB>();
            foreach (UserDB u in login)
            {
                Session[Global.SESS_SECURITY_CODE] = u;

            }
            Session.Timeout = 120;
            UserDB user_obj = (UserDB)Session[Global.SESS_SECURITY_CODE];
            if (user_obj != null)
            {
                hdfTrangthai.Value = "<a href=" + '"' + templatePath + "/Ca-nhan/Hom-nay/Bang-tin.html" + '"' + "style=" + '"' + "color:White" + ";text-decoration:None" + '"' + " class=" + '"' + "login-window1" + '"' + ">" + user_obj.UserName + " </a>";
                hdfCanhan.Value = "<a href=" + '"' + templatePath + "/trangchu/page/thoat.html" + '"' + "style=" + '"' + "color:White" + ";text-decoration:None" + '"' + " class=" + '"' + "login1-window1" + '"' + ">Thoát </a>";
                link1.Visible = false;
            }
        }

        int kiemtraId()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            int id = 0;
            var list = from k in dx.UserDBs
                       where k.UserName == txtChidinh.Text.Trim()
                       select k;
            foreach (UserDB ud in list)
                id = ud.ID;

            return id;
        }

        int kiemtraGioithieu()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            int id = 0;
            var list = from k in dx.UserDBs
                       where k.UserName == txtIntroduct.Text.Trim()
                       select k;
            foreach (UserDB ud in list)
                id = ud.ID;

            return id;
        }

        int kiemtraUsername()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            int id = 0;
            var list = from k in dx.UserDBs
                       where k.UserName == txtUser.Text.Trim()
                       select k;
            foreach (UserDB ud in list)
                id = ud.ID;

            return id;
        }

        int kiemtraEmail()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            int id = 0;
            var list = from k in dx.UserDBs
                       where k.email == txtEmai.Text.Trim()
                       select k;
            foreach (UserDB ud in list)
                id = ud.ID;

            return id;
        }

        protected void btn_Click(object sender, EventArgs e)
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            UserDB u = new UserDB();
            u.address = txtAdress.Text;
            u.bandau = cbCapbac.Text;
            u.capbac = cbCapbac.Text;
            u.cmnd = txtCMND.Text.Trim();
            u.email = txtEmai.Text;
            u.FirtName = txtTen.Text;
            u.Lastname = txtfisnam.Text.Trim();

            u.flag = 1;
            u.gioitinh = cbGioitinh.Text;
            u.kichhoat = false;
            if (cbCapbac.Text == "Cộng Tác Viên")
                u.maCB = "CTV";
            else
                u.maCB = "";
            u.maTV = "MS" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Millisecond;
            u.namsinh = int.Parse(cbNam.Value.ToString());
            u.thangsinh = int.Parse(cbThang.Value.ToString());
            u.ngaysinh = int.Parse(cbNgay.Value.ToString());
            u.officename = txtTennganhang.Text;
            u.nguoigioithieu = txtIntroduct.Text;
            u.Fullname = txtChidinh.Text;
            u.Password = Global.ToEncoding(txtPass.Text.Trim());
            u.phone = txtPhone.Text;
            u.UserName = txtUser.Text.Trim();
            u.visa = txtVisa.Text.Trim();
            u.ngaythamgia = DateTime.Now;
            u.ngaydangky = DateTime.Now;
            u.photo = "noimage.png";
            int id = kiemtraId();
            u.parentID = id;
            if (id == 0)
            {
                lbThongbao.Text = "Tài khoản chỉ định này không tồn tại, vui lòng nhập tài khoản khác";
                lberoo.Visible = true;
                lbThongbao.Visible = true;
            }
            else
            {
                lbThongbao.Visible = false;
                lberoo.Visible = false;
            }
            int gth = kiemtraGioithieu();
            if (gth == 0)
            {
                lbThongbao.Text = "Tài khoản giới thiệu này không tồn tại, vui lòng nhập tài khoản khác";
                lberoo.Visible = true;
                lbThongbao.Visible = true;
            }

            int em = kiemtraEmail();
            if (em > 0)
            {
                lbThongbao.Text = "Địa chỉ email này đã tồn tại, vui lòng nhập email khác";
                lberoo.Visible = true;
                lbThongbao.Visible = true;
            }

            int usn = kiemtraUsername();
            if (usn > 0)
            {
                lbThongbao.Text = "Tài khoản này đã tồn tại, vui lòng nhập tài khoản khác";
                lberoo.Visible = true;
                lbThongbao.Visible = true;
            }
            if (id > 0 && gth > 0 && usn == 0 && em==0)
            {
                dx.UserDBs.InsertOnSubmit(u);
                dx.SubmitChanges();
               // string tieude="Msmart thông báo! tài khoản của bạn vừa được đăng ký thành công";
               // string body = "<html><p>Chúc mừng "+txtfisnam+" "+txtTen +" đã đăng ký thành công tài khoản "+ txtUser.Text+" tại hệ thống Msmart.vn</p></html>";
                //GoogleMail.Send(txtEmai.Text.Trim(), tieude, body);
             
                Sendmail_Click(sender, e);
                lbThongbao.Visible = false;
                lberoo.Visible = false;
                dii.Visible = true;
                cc.Visible = false;
                pcCreateAccount.Height = 200;
                pcCreateAccount.HeaderText = "Đăng ký tài khoàn thành công";
                pcCreateAccount.Width = 600;
            }
           
        }

        void binngaysinh()
        {
            for (int i = 1; i <= 31;i++ )
                cbNgay.Items.Add("Ngày " + i, i);
            cbNgay.SelectedIndex = 0;
            for (int i = 1; i <= 12; i++)
                cbThang.Items.Add("Tháng " + i, i);
            cbThang.SelectedIndex = 0;
            for (int i = 1950; i <= 2010; i++)
                cbNam.Items.Add("Năm " + i, i);
            cbNam.SelectedIndex = 20;
        }

    

        public void sendmail(string from, string to,  string subject, string body)
        {
            MailMessage mailMsg = new MailMessage();
            mailMsg.From = new MailAddress(from, "Nguyễn Tiến Nghĩa"); 
            mailMsg.To.Add(to);

            //mailMsg.CC.Add(cc);  // cái này ko cần thiết lắm
            //mailMsg.Bcc.Add(bcc);// cái này ko cần thiết lắm
            mailMsg.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
            mailMsg.Subject = subject;
            mailMsg.IsBodyHtml = true;
            mailMsg.Body = body;
            mailMsg.Priority = MailPriority.Normal;
           
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            NetworkCredential info = new NetworkCredential("thinhvuongphatdat@gmail.com", "bietchetliennha");
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = info;
            client.EnableSsl = true;
            client.Send(mailMsg);
            
            System.Threading.Thread.Sleep(3000);

        }

        protected void Sendmail_Click(object sender, EventArgs e)
        {
            this.sendmail("thinhvuongphatdat@gmail.com", txtEmai.Text.Trim(), "Msmart thông báo! Tài khoản của bạn đã được đăng ký", "Xin chúc mừng "+cbCapbac.Text.ToLower()+" "+txtfisnam.Text+" "+txtTen.Text+" đã đăng ký thành công tài khoản "+txtUser.Text+" tại hệ thống Msmart.vn");

        }

    }
}